import { getToken, setToken, removeToken } from '@/utils/auth'
import { login } from '@/api/table'

const state = {
  token: getToken(),
  name: 1111
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  RESET_STATE: (state, token) => {
    state.token = token
  }
}

const actions = {
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username, password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  resetToken ({ commit }) {
    return new Promise((resolve) => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}
export default {
  state,
  mutations,
  actions
}
